<template>
  <div class="file-upload">
    <el-dialog :visible.sync="visible" :multiple="multiple" :result="result" :show="show" @close="$emit('update:show', false)">
      <div style="position: relative">
        <el-button @click="handlerSuccess(checkList)" type="primary" v-if="checkList.length>0" style=" position: absolute; top: 0px; right: 0; z-index: 999; ">确定选择</el-button>
        <el-tabs v-model="tabActive" @tab-click="handleTabsClick">
          <el-tab-pane label="文件上传" name="upload">
            <el-upload action="/api/basic/uploadFile" class="upload-demo" drag
                       :headers="{'X-Token':token}"
                       :file-list="fileList"
                       :before-upload="beforeUpload"
                       :on-success="onSuccess"
                       :on-error="onError"
                       :multiple="uploadMultiple"
                       :limit="5"
                       :on-exceed="onExceed" style="width: 100%">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">可任意上传文件</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="图片管理" name="image">
            <el-checkbox-group v-model="checkList" >
            <el-row :gutter="10">
                <el-col :span="6" v-for="(o, index) in list" :key="index" >
                  <el-card :body-style="{ padding: '10px' }">
                    <img :src="o.path" class="image" style=" width: 100%; height: 200px; ">
                    <div>
                      <div style="display: flex">
                      <div style="width: 100%">大小:{{o.size| fileSize }} </div>
                      <div style=" float: right; ">
                        <el-checkbox v-if="uploadMultiple" :label="o.path" size="medium">选择</el-checkbox>
                        <el-button size="mini" v-else type="success" icon="el-icon-check" circle @click="handlerSuccess([o.path])"></el-button>
                      </div>
                      </div>
                      <div class="bottom clearfix">
                        <time class="time">{{ o.created |parseTime}}</time>
                      </div>
                    </div>
                  </el-card>
                </el-col>
            </el-row>
                          </el-checkbox-group>
            <pagination v-if="page.total!=0" :total="page.total" :page.sync="page.page" :limit.sync="page.size" @pagination="initFileList" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import Pagination from '@/components/Pagination'
export default {
  name: 'FileUpload',
  components: { Pagination },
  filters:{
    fileSize(size){
      if(size<1024) return size+'b'
      size= size/1024
      if(size<1024)return size.toFixed(2)+'Kb';
      size=size/1024
      if(size<1024) return size.toFixed(2)+'Mb';
      size=size/1024
      if(size<1024) return size.toFixed(2)+'Gb';
    }
  },
  data() {
    return {
      tabActive:'upload',
      token:'',
      visible: this.show,
      list: [],
      fileList: [],
      uploadMultiple: this.multiple,
      page: { page: 1, size: 20,total:0 },
      uploadSize:0,
      checkList:[]
    }
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    result: Function
  },
  watch: {
    show() {
      this.selectedData = []
      this.visible = this.show
      if (this.visible == false) {
        this.fileList = []
      }
    },
    multiple() {
      this.uploadMultiple = this.multiple
    }
  },
  created() {
    this.token=this.$store.getters.token
    this.checkList=[]
  },
  mounted() {
    this.uploadSize=0;
  },
  methods: {
    handleTabsClick() {
      if (this.tabActive === 'upload')
        this.uploadSize = 0;
      else if(this.tabActive==='image'){
        this.initFileList()
      }
      console.log('handleTabsClick')
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return true
    },
    onExceed(file, fileList) {
      this.$message.error('一次最多只能选择5个文件')
    },
    onSuccess(response, file, fileList) {
      console.log('上传成功返回事件', response, file, fileList)
      this.uploadSize++;
      if(this.uploadSize>=fileList.length) {
        let array = [];
        fileList.forEach((e)=> {
          array.push(e.response.data)
        })
        this.handlerSuccess(array)
      }
    },
    onError(error) {
      console.log('上传出现了错误,', error)
      this.$message.error(error.message)
    },

    handlerSuccess(rows){
      console.log('确认选中返回',rows)
      this.visible=false;
      this.result(rows)
    },

    /** 获取图片列表
      */
    initFileList(){
      this.$api.get('/api/basic/uploadFile',this.page).then(res=>{
        this.list=res.data;
        this.page.total=res.total;
      })
    }

  }
}
</script>
<style lang='scss' scoped>
.file-upload{
  .el-card{
    margin-bottom: 10px;
  }
  .el-checkbox-group{
    font-size: 14px;
  }
  .el-upload {
    width: 100%;
  }
  .el-upload-dragger{
    width: 100%;
  }
}
</style>


